package cn.melonlib.cores.graphql.comp.web.utils;

import cn.hutool.core.io.IoUtil;
import cn.melonlib.cores.graphql.comp.web.bean.GraphqlArguments;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class GraphqlArgumentsUtils {


    private ThreadLocal<GraphqlArguments> graphqlArgumentsThreadLocal=new ThreadLocal<>();

    @Resource
    private ObjectMapper jsonMapper;

    public void init(HttpServletRequest request) throws Exception{
        try(InputStream in = request.getInputStream()) {
            String params=IoUtil.read(in, StandardCharsets.UTF_8);
            graphqlArgumentsThreadLocal.set(jsonMapper.readValue(params, GraphqlArguments.class));
        }
    }

    public GraphqlArguments getArguments(){
        return this.graphqlArgumentsThreadLocal.get();
    }

    public void clean(){
        this.graphqlArgumentsThreadLocal.remove();
    }

}
